#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <sys/ioctl.h>
#include <netdb.h>

#include "hi_appcomm.h"
#include "hi_ext_util.h"
#include "plug_common.h"
#include "plug_comm_gesture.h"
#include "plug_mqtt.h"
#include "plug_datamng.h"
#include "osd_img.h"
#include "plug_hisignalling.h"
#include "plug_detectmng.h"
#include "plug_stream.h"
#include "plug_media_ao.h"
#include "plug_media_ai.h"
#include "plug_media_recordmng.h"

#include "plug_lte.h"
#include "plug_gpio.h"
#include "plug_media_photomng.h"

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* End of #ifdef __cplusplus */

//水印大小
#define OSD_FONT_WIDTH     16
#define OSD_FONT_HEIGHT    24

//警报间隔时间（同一种类）
#define PLUG_COMMON_SOUND_INTERVAL    5

typedef struct tagPLUG_COMMON_SUB_LIST
{
    const HI_CHAR *pazTopic;
    HI_S32 s32Qos;
}PLUG_COMMON_SUB_LIST;

typedef struct tagPLUG_COMMON_PUB_LIST
{
    PLUG_COMMON_PUB_LIST_TYPE_E enType;
    const HI_CHAR *pazTopic;
    HI_S32 s32Qos;
}PLUG_COMMON_PUB_LIST;

static PLUG_COMMON_SUB_LIST stPlugSublist[] =
{
    {"/service/register",1},
    {"/service/rt_video",2},
    {"/service/rt_talk", 2},
};

static PLUG_COMMON_PUB_LIST stPlugPublist[PLUG_COMMON_DEVICE_BUTT] =
{
        {PLUG_COMMON_DEVICE_REGISTER, "/device/register",1},
        {PLUG_COMMON_DEVICE_RT_VIDEO, "/device/rt_video", 0},
        {PLUG_COMMON_DEVICE_HEARTBEAT, "/device/heartbeat", 0},

    #if (defined(HI_COMM_AI_ADAPT_DOOR))
        {PLUG_COMMON_DEVICE_TEMPERATURE, "/door/device/temperature", 0},
        {PLUG_COMMON_DEVICE_HUMIDITY, "/door/device/humidity", 0},
        {PLUG_COMMON_DEVICE_SMOKE, "/door/device/smoke", 0},
        {PLUG_COMMON_DEVICE_PHOTO, "/door/device/photo", 0},

    #elif (defined(HI_COMM_AI_ADAPT_GUIDER))
        {PLUG_COMMON_DEVICE_DISTANCE_AHEAD, "/blindguide/device/distance", 0},
        {PLUG_COMMON_DEVICE_DISTANCE_BELOW, "/blindguide/device/distance", 0},
        {PLUG_COMMON_DEVICE_GPS_LONGGITUDE, "/blindguide/device/gps", 0},
        {PLUG_COMMON_DEVICE_DETECT, "/blindguide/device/detect", 0},
        
    #endif
};

static pthread_t s_MqttTaskId = 0;//mqtt连接的线程ID
static pthread_t s_MqttHeartId = 0;//心跳的线程ID

static HI_BOOL bMqttConnecTask = HI_FALSE;//正在连接mqtt标志
static OsdSet* s_pstOsdSet[PLUG_COMMON_MOD_BUTT]; //水印句柄
static HI_BOOL bMqttConnect = HI_FALSE;//mqtt连接标志
static HI_BOOL s_bMqttHeatFlag = HI_FALSE;//心跳线程是否启动
static PLUG_COMMON_DEV_INFO_S s_stDevInfo = {0};
static PLUG_COMMON_DATA_INFO_S s_stPegesusData = {0};

static HI_S32 COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_E enType)
{
    HI_S32 s32Ret = HI_SUCCESS;
    HI_S32 bPlayRet = HI_TRUE;
    time_t now = 0;
    static time_t lastTime[PLUG_MEDIA_AO_SOUND_BUTT] = {0};
    
    time(&now);
    
    if ((PLUG_MEDIA_AO_SOUND_HEAD < enType) || (PLUG_MEDIA_AO_SOUND_BUTT > enType))
    {
        if ((now - lastTime[enType]) > PLUG_COMMON_SOUND_INTERVAL)
        {
            lastTime[enType] = now;
            
            s32Ret = PLUG_MEDIA_AO_SystemSound(enType);
            if (HI_SUCCESS != s32Ret)
            {
                LOGE("PLUG_MEDIA_AO_SystemSound failed!\n");
                return HI_FAILURE;
            }
        }
    }
    
    return HI_SUCCESS;
}

static HI_VOID* PLUG_COMMON_MQTT_Init(HI_VOID)
{
    HI_S32 s32Ret = HI_SUCCESS;
    HI_S32 s32Idx = 0;
    
    s32Ret = PLUG_MQTT_Connect();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MQTT_Connect failed! %d\n", s32Ret);
        bMqttConnecTask = HI_FALSE;
        return HI_NULL;
    }

    for(s32Idx = 0; s32Idx < sizeof(stPlugSublist)/sizeof(PLUG_COMMON_SUB_LIST); s32Idx++)
    {
        //订阅消息类型
        s32Ret = PLUG_MQTT_SubClient(stPlugSublist[s32Idx].pazTopic, stPlugSublist[s32Idx].s32Qos);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("PLUG_MQTT_SubClient failed! %s %d\n", stPlugSublist[s32Idx].pazTopic, s32Ret);
        }
    }

    //发布设备注册话题
    s32Ret = PLUG_COMMON_GetDeviceInfo(&s_stDevInfo);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_GetDeviceInfo error!\n");
        return HI_FAILURE;
    }

    bMqttConnect = HI_TRUE;
    s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_REGISTER, s_stDevInfo.azDeviceId);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
    }

	
    bMqttConnecTask = HI_FALSE;
    
    return HI_NULL;
}
static HI_VOID* PLUG_COMMON_MQTT_Heart(HI_VOID)
{
    HI_S32 s32Ret = HI_SUCCESS;

    //发布心跳话题
    s32Ret = PLUG_COMMON_GetDeviceInfo(&s_stDevInfo);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_GetDeviceInfo error!\n");
        return HI_FAILURE;
    }
    
    HI_S32 count=0;

    while(bMqttConnect ==  HI_TRUE)
    {
        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_HEARTBEAT, s_stDevInfo.azDeviceId);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
        }
        else
        {
            LOGD("pthread PLUG_COMMON_MQTT_Heart send %d times!\n",count++);
        }

        sleep(30);
        // sleep(1);

    }
    s_bMqttHeatFlag = HI_FALSE;
}
/* 创建发送心跳线程保持mqtt连接 */
 HI_S32 PLUG_COMM_CreateMqttHeartThread()
 {
     HI_S32 s32Ret = HI_SUCCESS;

     if(s_bMqttHeatFlag == HI_FALSE)
     {
        s_bMqttHeatFlag = HI_TRUE;
        s32Ret = pthread_create(&s_MqttHeartId, HI_NULL, PLUG_COMMON_MQTT_Heart, HI_NULL);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("pthread create PLUG_COMMON_MQTT_Heart failed!\n");
        }
     }
     return HI_SUCCESS;
 }
 HI_S32 PLUG_COMM_GetLoaclIP(HI_CHAR *pazIP)
 {
     HI_APPCOMM_CHECK_POINTER(pazIP, HI_FAILURE);
     HI_S32 s32NetSock;
     struct ifreq stIfr;
     HI_CHAR azIp[32]={ 0 };
 
     s32NetSock = socket(AF_INET, SOCK_DGRAM, 0);
     strcpy(stIfr.ifr_name, "eth0");
     ioctl(s32NetSock, SIOCGIFADDR, &stIfr);
     strcpy(azIp, inet_ntoa(((struct sockaddr_in *)&stIfr.ifr_addr)->sin_addr));
     close(s32NetSock);
     LOGI("Local eht0 :%s\n", azIp);
     sprintf(pazIP, "%s", azIp);
     return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_CheckFolderExist(const HI_CHAR *pazFolder)
{
    if (HI_NULL == pazFolder)
    {
        LOGI("input null\n");
        return HI_FAILURE;
    }
    HI_S32 s32Ret = HI_SUCCESS;
    s32Ret = access(pazFolder, R_OK | W_OK);
    if (HI_SUCCESS == s32Ret)
    {
        //目录存在，且可读可写
        return HI_SUCCESS;
    }
    else
    {
        HI_CHAR azCmd[64];
        snprintf(azCmd, sizeof(azCmd), "mkdir -p %s", pazFolder);
        system(azCmd);
        snprintf(azCmd, sizeof(azCmd), "chmod 777 %s", pazFolder);
        system(azCmd);
    }

    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_Init(HI_VOID)
{
    HI_S32 s32Ret = HI_SUCCESS;
    PLUG_HISIGNALLING_INFO stInfo;
    PLUG_DETECTMNG_CFG_S stDetectMngCfg = { 0 };

    if ((access(PLUG_COMMON_DATAMNG_DEV_INFO_FILE_PATH, F_OK)) == -1)
    {
        LOGI("PLUG_DATAMNG_WriteConfig...\n");
        
        s32Ret = PLUG_DATAMNG_WriteConfig(PLUG_COMMON_DATAMNG_DEV_INFO_FILE_PATH, s_stDevInfo);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("HI_DATAMNG_WriteConfig failed!\n");
            return HI_FAILURE;
        }
    }
    else
    {
        s32Ret = PLUG_DATAMNG_ReadConfig(PLUG_COMMON_DATAMNG_DEV_INFO_FILE_PATH, &s_stDevInfo);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("HI_DATAMNG_WriteConfig failed!\n");
            return HI_FAILURE;
        }
    }

    system("/hiopenais/ntp/update_time.sh");

#if (defined(HI_COMM_AI_ADAPT_GUIDER))
    LTE_EVENT Event;
    Event.pfnEvent = PLUG_DETECT_KEY_Init;
    HI_HAL_LTE_Init(&Event);
#endif

#if (defined(HI_COMM_AI_ADAPT_GESTURE))
    s32Ret = PLUG_COMM_GESTURE_Init();
    HI_APPCOMM_CHECK_EXPR((HI_SUCCESS == s32Ret), HI_FAILURE);
#else
    /* 创建线程启动mqtt连接 */
    if (HI_FALSE == bMqttConnecTask)
    {
        bMqttConnecTask = HI_TRUE;
        s32Ret = pthread_create(&s_MqttTaskId, HI_NULL, PLUG_COMMON_MQTT_Init, HI_NULL);
        if (HI_SUCCESS != s32Ret)
        {
            LOGE("pthread create PLUG_COMMON_MQTT_Init failed!\n");
        }
    }
#endif

#if (defined(HI_COMM_AI_ADAPT_DOOR))
    stDetectMngCfg.s32ClassNum = 9;
#elif (defined(HI_COMM_AI_ADAPT_GESTURE))
    stDetectMngCfg.s32ClassNum = 25;
#elif (defined(HI_COMM_AI_ADAPT_GUIDER))
    stDetectMngCfg.s32ClassNum = 8;
#endif

    stDetectMngCfg.s32DetectIntervalMs = PLUG_COMMON_DETECT_INTERVAL_MS;
    s32Ret = PLUG_DETECTMNG_Init(&stDetectMngCfg);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_DETECTMNG_Init failed!\n");
    }

    stInfo.pfnRecMsg = PLUG_COMMON_RecvMsg;
    stInfo.pfnSenMsg = PLUG_COMMON_SendMsg;

    s32Ret = PLUG_HISIGNALLING_Init(stInfo);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_HISIGNALLING_Init failed!\n");
    }
    
    PLUG_MEDIA_AI_INFO stAiInfo;
    stAiInfo.pfnRecMsg = PLUG_STREAM_SendAudioFrame;
    stAiInfo.pfnRecordMsg = PLUG_MEDIA_RecordSendAudioFrame;
    s32Ret = PLUG_MEDIA_AI_Init(stAiInfo);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AI_Init failed!\n");
    }
    s32Ret = PLUG_MEDIA_AI_Start();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AI_Start failed!\n");
    }
    
    s32Ret = PLUG_MEDIA_AO_Init(PT_AAC);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AO_Init failed!\n");
    }
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_GetDataInfo(PLUG_COMMON_DATA_INFO_S *pstInfo)
{
    HI_APPCOMM_CHECK_POINTER(pstInfo, HI_NULL);
    
    HI_S32 s32Ret = HI_SUCCESS;
    
    memcpy(pstInfo, &s_stPegesusData, sizeof(PLUG_COMMON_DATA_INFO_S));
    
    return HI_SUCCESS;
}


HI_S32 PLUG_COMMON_RecvMsg(HI_U8 *pu8Payload)
{
    HI_S32 s32Ret = HI_SUCCESS;

    HI_U8 pu8Msg[255];
    HI_U8 u8Type[64] = {0};
    HI_U8 u8Data[64] = {0};
    HI_CHAR* pazSplit = HI_NULL;
    HI_CHAR* ps;
    PLUG_COMMON_PUB_LIST_TYPE_E st_PegesusType;

#if (defined(HI_COMM_AI_ADAPT_DOOR))
    /* 机柜门 */
    HI_S32 temperature_warn = 0;
    HI_S32 humidity_warn = 0;
    HI_S32 smoke_warn = 0;
    
    HI_S8 payload[64] = "";

 #elif (defined(HI_COMM_AI_ADAPT_GUIDER))
    /* 导盲仪 */
    HI_S8 payload[64] = "";  

    HI_S32 ahead_warn = 1;
    HI_S32 below_warn = 1;
 #endif
    
    //获得设备信息
    s32Ret = PLUG_COMMON_GetDeviceInfo(&s_stDevInfo);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_GetDeviceInfo error!\n");
        return HI_FAILURE;
    }
    
    HI_DOUBLE data;
    
    snprintf(pu8Msg, sizeof(pu8Msg), pu8Payload);

    pazSplit = strstr(pu8Msg, "/");

    if ((pazSplit != HI_NULL) && (strlen(pazSplit) > 1))
    {
        memcpy(u8Type, pu8Msg, (strlen(pu8Msg) - strlen(pazSplit)));
        
        st_PegesusType = atoi(u8Type);

        memcpy(u8Data, pazSplit + 1, strlen(pazSplit) - 1);

        data = strtod(u8Data,&ps);

        switch(st_PegesusType){
             #if (defined(HI_COMM_AI_ADAPT_DOOR))
                case PLUG_COMMON_DEVICE_TEMPERATURE:
                {
                    if(data > s_stDevInfo.s32TempThres)
                    {
                        temperature_warn = 1;
                        s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_TEMPERATURE);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                        }
                    }
                    else
                    {
                        temperature_warn = 0;
                    }
                    
                    if(s_stPegesusData.dTemperature != data)
                    {
                        s_stPegesusData.dTemperature = data;
                        
                        LOGD("s_stPegesusData.dTemperature = %.2f ,s_stDevInfo.s32TempThres = %d\n", s_stPegesusData.dTemperature,s_stDevInfo.s32TempThres);
                        snprintf(payload, sizeof(payload), "%s/%.2f/%d", s_stDevInfo.azDeviceId, \
                            s_stPegesusData.dTemperature, temperature_warn);

                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_TEMPERATURE, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                    }
                }
                break;
                case PLUG_COMMON_DEVICE_HUMIDITY:
                {
                    if(data > s_stDevInfo.s32HumThres)
                    {
                        humidity_warn = 1;
                        s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_HUMIDITY);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                        }
                    }
                    else
                    {
                        humidity_warn = 0;
                    }
                
                    if(s_stPegesusData.dHumidity != data)
                    {
                        s_stPegesusData.dHumidity = data;
                        LOGD("s_stPegesusData.dHumidity = %.2f ,s_stDevInfo.s32HumThres = %d\n", s_stPegesusData.dHumidity,s_stDevInfo.s32HumThres);
                        snprintf(payload, sizeof(payload), "%s/%.2f/%d", s_stDevInfo.azDeviceId, \
                            s_stPegesusData.dHumidity, humidity_warn);
                        
                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_HUMIDITY, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                    }
                }
                    break;
                case PLUG_COMMON_DEVICE_SMOKE:
                {
                    if(((data-300)/20) > s_stDevInfo.s32SmokeThres) /* 检测到有烟 */
                    {
                        s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_SMOKE);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                        }
                    }
                    
                    if(s_stPegesusData.dSmoke != data)
                    {
                        s_stPegesusData.dSmoke = data;

                        if(((s_stPegesusData.dSmoke-300)/20) > s_stDevInfo.s32SmokeThres)
                        {
                            smoke_warn = 1;
                        }

                        snprintf(payload, sizeof(payload), "%s/%d", s_stDevInfo.azDeviceId, smoke_warn);

                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_SMOKE, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                    }
                }
                    break;
                                
                #elif (defined(HI_COMM_AI_ADAPT_GUIDER))
                    case PLUG_COMMON_DEVICE_DISTANCE_AHEAD:
                    {
                        /* 测距报警判断 */
                        /*
                        超声波类型   测距范围     判断结果   返回结果
                        前方超声波      0.0-3.0m    前方有障碍   0
                                        >3.0m       前方安全    1

                        下方超声波     0.0m-1.2m    下方有障碍   0
                                        1.0m-1.2m   下方安全    1
                                        >1.2m       下方有坑    2
                        */
                                    
                        /*  设备ID/下测距警报 前测距警报 (eg:000001/1 0)  
                        
                        下测距警报 :0:下方有障碍；1:下方安全；2:下方有坑；前测距警报:0:前方有障碍；1:前方安全
                        */
                        if(s_stPegesusData.dDistance_aHead < 300)
                        {
                            s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_DISTANCE_AHEAD);
                            if (HI_SUCCESS != s32Ret)
                            {
                                LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                            }
                        }
                        
                        //上下波动超过5cm才会发送警告到服务器
                        if(((int)s_stPegesusData.dDistance_aHead-(int)data >5) || ((int)s_stPegesusData.dDistance_aHead-(int)data <-5))
                        {
                            s_stPegesusData.dDistance_aHead = data;
                                
                            if(s_stPegesusData.dDistance_Below >= s_stDevInfo.s32DisBlowWarnLow && s_stPegesusData.dDistance_Below <= s_stDevInfo.s32DisBlowWarnHight)
                            {
                                below_warn = 1;
                            }
                            else if(s_stPegesusData.dDistance_Below < s_stDevInfo.s32DisBlowWarnLow) 
                            {
                                below_warn = 0;
                            }
                            else 
                            {
                                below_warn = 2;
                            }
                        
                            if(s_stPegesusData.dDistance_aHead > s_stDevInfo.s32DisAheadWarn)
                            {
                                ahead_warn = 1;
                            }
                            else
                            {
                                ahead_warn = 0;
                            }
                        
                            snprintf(payload, sizeof(payload), "%s/%d %d", s_stDevInfo.azDeviceId, below_warn, ahead_warn);
                        
                            s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_DISTANCE_AHEAD, payload);
                            if (HI_SUCCESS != s32Ret)
                            {
                                LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                            }
                        }
                        
                    }
                    break;
                case PLUG_COMMON_DEVICE_DISTANCE_BELOW:
                {
                    if(data < s_stDevInfo.s32DisBlowWarnLow) 
                    {
                        s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_DISTANCE_BELOW);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                        }
                    } 
                    else if (data > s_stDevInfo.s32DisBlowWarnHight)
                    {
                        s32Ret = COMMON_SystemSound(PLUG_MEDIA_AO_SOUND_DISTANCE_BELOW_PIT);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("COMMON_SystemSound failed! %d\n", s32Ret);
                        }
                    }
                
                    //上下波动超过5cm才会发送警告到服务器
                    if(((int)s_stPegesusData.dDistance_Below-(int)data >5) || ((int)s_stPegesusData.dDistance_Below-(int)data <-5))
                    {
                        s_stPegesusData.dDistance_Below = data;

                        if(s_stPegesusData.dDistance_Below >= s_stDevInfo.s32DisBlowWarnLow && s_stPegesusData.dDistance_Below <= s_stDevInfo.s32DisBlowWarnHight)
                        {
                            below_warn = 1;
                        }
                        else if(s_stPegesusData.dDistance_Below < s_stDevInfo.s32DisBlowWarnLow) 
                        {
                            below_warn = 0;
                        }
                        else 
                        {
                            below_warn = 2;
                        }

                        if(s_stPegesusData.dDistance_aHead > s_stDevInfo.s32DisAheadWarn)
                        {
                            ahead_warn = 1;
                        }
                        else
                        {
                            ahead_warn = 0;
                        }

                        snprintf(payload, sizeof(payload), "%s/%d %d", s_stDevInfo.azDeviceId, below_warn,ahead_warn);
            
                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_DISTANCE_BELOW, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                    } 
                }
                    break;
                case PLUG_COMMON_DEVICE_GPS_LONGGITUDE:
                    if(s_stPegesusData.dGpsLongitude != data){
                        s_stPegesusData.dGpsLongitude = data;
                        
                        snprintf(payload, sizeof(payload), "%s/%.6f %.6f", s_stDevInfo.azDeviceId, \
                            s_stPegesusData.dGpsLongitude, s_stPegesusData.dGpslatitude);

                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_GPS_LONGGITUDE, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                        
                    }
                    break;
                case PLUG_COMMON_DEVICE_GPS_LATITUDE:
                    if(s_stPegesusData.dGpslatitude != data){
                        s_stPegesusData.dGpslatitude = data;

                        snprintf(payload, sizeof(payload), "%s/%.6f %.6f", s_stDevInfo.azDeviceId, \
                            s_stPegesusData.dGpsLongitude, s_stPegesusData.dGpslatitude);

                        s32Ret = PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_DEVICE_GPS_LATITUDE, payload);
                        if (HI_SUCCESS != s32Ret)
                        {
                            LOGE("PLUG_COMMON_MQTT_PubClient failed! %d\n", s32Ret);
                        }
                    }
                    break;
                #endif
                        
                default:
                    break;
                
        }     
    }
    return HI_SUCCESS;    
}

HI_S32 PLUG_COMMON_SendMsg(HI_S32 fd, HI_VOID *buf)
{
    hisignalling_msg_send(fd, buf, 4);
}

HI_S32 PLUG_COMMON_TakePhoto(HI_VOID)
{
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_OsdsClear(PLUG_COMMON_MOD_E enMod)
{
    if (enMod >= PLUG_COMMON_MOD_BUTT || enMod < PLUG_COMMON_MOD_LCD)
    {
        LOGE("enMod is error! %d\n", enMod);
        return HI_FAILURE;
    }
    
    if (s_pstOsdSet[enMod] != HI_NULL)
    {
        OsdsClear(s_pstOsdSet[enMod]);
    }
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_UpdateOsdInfo(PLUG_COMMON_MOD_E enMod, PLUG_COMMON_OSD_INFO* pstOsdInfo)
{
    HI_APPCOMM_CHECK_POINTER(pstOsdInfo, HI_NULL);
    
    if (enMod >= PLUG_COMMON_MOD_BUTT || enMod < PLUG_COMMON_MOD_LCD)
    {
        LOGE("enMod is error! %d\n", enMod);
        return HI_FAILURE;
    }
    
    HI_OSD_ATTR_S osdRgn;
    HI_S32 osdId = 0;
    
    if (s_pstOsdSet[enMod] != HI_NULL)
    {
        osdId = OsdsCreateRgn(s_pstOsdSet[enMod]);
        if (osdId < 0)
        {
            LOGE("OsdsCreateRgn failed!\n");
            return HI_FAILURE;
        }
        
        switch(pstOsdInfo->enType)
        {
            case PLUG_COMMON_OSD_TIME:
            {
                /* 设置  时间水印 */
                TimeRgnInit(&osdRgn, HI_TRUE, pstOsdInfo->u32XCoordinate, \
                            pstOsdInfo->u32YCoordinate, pstOsdInfo->u32Color, pstOsdInfo->s32FontWidth, pstOsdInfo->s32FontHeight);
                OsdsSetRgn(s_pstOsdSet[enMod], osdId, &osdRgn);
                break;
            }
            case PLUG_COMMON_OSD_STRING:
            {
                /* 设置  字符串水印 */
                TxtRgnInit(&osdRgn, pstOsdInfo->azString, pstOsdInfo->u32XCoordinate, \
                            pstOsdInfo->u32YCoordinate, pstOsdInfo->u32Color, pstOsdInfo->s32FontWidth, pstOsdInfo->s32FontHeight);
                OsdsSetRgn(s_pstOsdSet[enMod], osdId, &osdRgn);
                break;
            }
            default:
            {
                LOGE(" Unsupported osd type %d\n", pstOsdInfo->enType);
                break;
            }
        }
    }
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_SetOsdSet(PLUG_COMMON_MOD_E enMod, OsdSet* pstOsdSet)
{
    if (enMod < PLUG_COMMON_MOD_BUTT)
    {
        s_pstOsdSet[enMod] = pstOsdSet;
    }
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_GetDeviceInfo(PLUG_COMMON_DEV_INFO_S *pstInfo)
{
    HI_APPCOMM_CHECK_POINTER(pstInfo, HI_NULL);
    
    HI_S32 s32Ret = HI_SUCCESS;
    
    memcpy(pstInfo, &s_stDevInfo, sizeof(PLUG_COMMON_DEV_INFO_S));
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_SetDeviceInfo(PLUG_COMMON_DEV_INFO_S stInfo)
{
    HI_S32 s32Ret = HI_SUCCESS;
    
    s32Ret = PLUG_DATAMNG_WriteConfig(PLUG_COMMON_DATAMNG_DEV_INFO_FILE_PATH, stInfo);
    if(s32Ret != HI_SUCCESS)
    {
        LOGE("PLUG_DATAMNG_WriteConfig failed\n");
        return HI_FAILURE;
    }
    
    memcpy(&s_stDevInfo, &stInfo, sizeof(PLUG_COMMON_DEV_INFO_S));
    
    return HI_SUCCESS;
}

HI_S32 PLUG_COMMON_MQTT_PubClient(PLUG_COMMON_PUB_LIST_TYPE_E enPubType, HI_S8 *payload)
{
    HI_S32 s32Idx = 0;
    HI_S32 s32Ret = HI_SUCCESS;
    
    for (s32Idx = 0; s32Idx < PLUG_COMMON_DEVICE_BUTT; s32Idx++)
    {
        if (enPubType == stPlugPublist[s32Idx].enType)
        {
            /* 根据消息类型找到 要发送的主题，然后进行发送 */
            s32Ret = PLUG_MQTT_PubClient(stPlugPublist[s32Idx].pazTopic, \
                    payload, stPlugPublist[s32Idx].s32Qos, 0);
            if(s32Ret != HI_SUCCESS)
            {
                LOGE("PLUG_MQTT_PubClient failed\n");
                return HI_FAILURE;
            }
            break;
        }
    }
    
    return HI_SUCCESS;
}

HI_VOID PLUG_COMM_TakePhoto()
{
    HI_S32 s32Ret = HI_SUCCESS;
    PLUG_MEDIA_PHOTOMNG_INITCFG_S stInitCfg;
    s32Ret = PLUG_MEDIA_PHOTOMNG_Init(&stInitCfg);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_PHOTOMNG_Init failed\n");
        return ;
    }

    s32Ret = PLUG_COMMON_CheckFolderExist(PLUG_COMMON_PHOTO_FOLDER);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_CheckFolderExist failed\n");
        return ;
    }

    PLUG_MEDIA_PHOTOMNG_CFG_S stPhotoCfg;
    time_t time_seconds = time(HI_NULL);
    struct tm stNowTime;
    localtime_r(&time_seconds, &stNowTime);

    sprintf(stPhotoCfg.azFilePath, "%s/%04d%02d%02d_%02d%02d%02d.jpg",
        PLUG_COMMON_PHOTO_FOLDER,
        stNowTime.tm_year + 1900, stNowTime.tm_mon + 1, stNowTime.tm_mday, 
        stNowTime.tm_hour, stNowTime.tm_min, stNowTime.tm_sec);
    s32Ret = PLUG_MEDIA_PHOTOMNG_TakePhoto(&stPhotoCfg);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_PHOTOMNG_TakePhoto failed\n");
    }

    s32Ret = PLUG_MEDIA_PHOTOMNG_Deinit();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_PHOTOMNG_Deinit failed\n");
    }

    return ;
}

HI_VOID PLUG_COMM_StartRecord()
{
    HI_S32 s32Ret = HI_SUCCESS;
    PLUG_MEDIA_RECORDMNG_INITCFG_S stInitCfg;
    s32Ret = PLUG_MEDIA_RECORDMNG_Init(&stInitCfg);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_RECORDMNG_Init failed\n");
        return ;
    }

    s32Ret = PLUG_COMMON_CheckFolderExist(PLUG_COMMON_VIDEO_FOLDER);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_COMMON_CheckFolderExist failed\n");
        return ;
    }

    PLUG_MEDIA_RECORDMNG_CFG_S stRecordCfg;
    time_t time_seconds = time(HI_NULL);
    struct tm stNowTime;
    localtime_r(&time_seconds, &stNowTime);

    sprintf(stRecordCfg.azFilePath, "%s/%04d%02d%02d_%02d%02d%02d.mp4",
        PLUG_COMMON_VIDEO_FOLDER,
        stNowTime.tm_year + 1900, stNowTime.tm_mon + 1, stNowTime.tm_mday, 
        stNowTime.tm_hour, stNowTime.tm_min, stNowTime.tm_sec);
    s32Ret = PLUG_MEDIA_RECORDMNG_StartRecord(&stRecordCfg);
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_RECORDMNG_StartRecord failed\n");
    }

    return ;
}

HI_VOID PLUG_COMM_StopRecord()
{
    HI_S32 s32Ret = HI_SUCCESS;

    s32Ret = PLUG_MEDIA_RECORDMNG_StopRecord();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_RECORDMNG_StopRecord failed\n");
    }

    s32Ret = PLUG_MEDIA_RECORDMNG_Deinit();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_RECORDMNG_Deinit failed\n");
    }

    return ;
}

HI_BOOL PLUG_COMMON_GetRecodeState()
{
    return PLUG_MEDIA_RECORDMNG_GetState();
}

HI_S32 PLUG_COMMON_DeInit(HI_VOID)
{
    HI_S32 s32Ret = HI_SUCCESS;

#if (defined(HI_COMM_AI_ADAPT_GESTURE))
    s32Ret = PLUG_COMM_GESTURE_Deinit();
    HI_APPCOMM_CHECK_EXPR_WITHOUT_RETURN((HI_SUCCESS == s32Ret), "PLUG_COMM_GESTURE_Deinit failed");
#else
    //断开mqtt连接
    HI_S32 s32Idx = 0;
    
    for (s32Idx = 0; s32Idx < 10; s32Idx ++)
    {
        if (!bMqttConnecTask)
        {
            s32Ret = PLUG_MQTT_Disconnect();
            if (HI_SUCCESS != s32Ret)
            {
                LOGE("PLUG_MQTT_Disconnect failed! %d\n", s32Ret);
            }
            bMqttConnect = HI_FALSE;
            break;
        }
        
        usleep(100 * 1000);
    }
#endif

    s32Ret = PLUG_DETECTMNG_Deinit();
    HI_APPCOMM_CHECK_EXPR_WITHOUT_RETURN((HI_SUCCESS == s32Ret), "PLUG_DETECTMNG_Deinit failed");


    s32Ret = PLUG_MEDIA_AI_Stop();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AI_Stop failed!\n");
    }
    
    s32Ret = PLUG_MEDIA_AI_Deinit();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AI_Deinit failed!\n");
    }
    
    s32Ret = PLUG_MEDIA_AO_Deinit();
    if (HI_SUCCESS != s32Ret)
    {
        LOGE("PLUG_MEDIA_AO_Deinit failed!\n");
    }
    
    return HI_SUCCESS;
}

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* End of #ifdef __cplusplus */

